package com.chee.plant.client;

import java.nio.charset.Charset;

import org.apache.mina.common.IoFilter;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;

import com.chee.plant.server.Message;

public class ClientHandler extends IoHandlerAdapter {

    public interface Callback {
        void connected();
        void loggedIn();
        void loggedOut();
        void disconnected();
        void messageReceived(Message message);
        void error(Message message);
    }

    //private static IoFilter CODEC_FILTER = new ProtocolCodecFilter( new MessageCodecFactory());
    private static IoFilter CODEC_FILTER = new ProtocolCodecFilter(new TextLineCodecFactory( Charset.forName( "UTF-8" )));

    private final Callback callback;

    public ClientHandler(Callback callback) {
        this.callback = callback;
    }

    public void sessionCreated(IoSession session) throws Exception {
        session.getFilterChain().addLast("codec", CODEC_FILTER);
    }

    public void sessionOpened(IoSession session) throws Exception {
        callback.connected();
    }

    public void messageReceived(IoSession session, Object message)
            throws Exception {
    	String content = (String)message;
    	Message msg = new Message(content);
    	callback.messageReceived(msg);
    }

    public void sessionClosed(IoSession session) throws Exception {
        callback.disconnected();
    }
}
